/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * Project Name: lmrp-android app
 * Create Time: 16-2-16 下午6:28
 */

package com.lenovo.mso2o.biz;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.easemob.EMCallBack;
import com.igexin.sdk.PushManager;
import com.lenovo.framework.base.FBaseActivity;
import com.lenovo.framework.biz.ContextManager;
import com.lenovo.framework.biz.IAccountManager;
import com.lenovo.framework.entity.AccessToken;
import com.lenovo.framework.entity.Res;
import com.lenovo.framework.rest.NetworkObserver;
import com.lenovo.framework.util.DLog;
import com.lenovo.framework.util.FPreferenceManager;
import com.lenovo.mso2o.BuildConfig;
import com.lenovo.mso2o.MSApplication;
import com.lenovo.mso2o.R;
import com.lenovo.mso2o.conf.MSConstants;
import com.lenovo.mso2o.conf.MessageType;
import com.lenovo.mso2o.conf.SyncType;
import com.lenovo.mso2o.entity.EngineerDetailResponse;
import com.lenovo.mso2o.entity.LogoutRequest;
import com.lenovo.mso2o.entity.TokenRequest;
import com.lenovo.mso2o.entity.g.Ad;
import com.lenovo.mso2o.entity.g.AdDao;
import com.lenovo.mso2o.entity.g.Notification;
import com.lenovo.mso2o.entity.g.NotificationDao;
import com.lenovo.mso2o.entity.g.Project;
import com.lenovo.mso2o.entity.g.ProjectDao;
import com.lenovo.mso2o.entity.g.Site;
import com.lenovo.mso2o.entity.g.SiteDao;
import com.lenovo.mso2o.entity.g.StepIcon;
import com.lenovo.mso2o.entity.g.StepIconDao;
import com.lenovo.mso2o.entity.g.SyncCode;
import com.lenovo.mso2o.entity.g.SyncCodeDao;
import com.lenovo.mso2o.entity.g.SysDict;
import com.lenovo.mso2o.entity.g.SysDictDao;
import com.lenovo.mso2o.rest.AuthAPI;
import com.lenovo.mso2o.rest.OrderAPI;
import com.lenovo.mso2o.rest.OtherAPI;
import com.lenovo.mso2o.rest.ServiceGenerator;
import com.lenovo.mso2o.rest.UserAPI;
import com.lenovo.mso2o.service.AutoSignService;
import com.lenovo.mso2o.service.TickNetworkReceiver;
import com.lenovo.mso2o.service.UploadService;
import com.lenovo.mso2o.ui.LoginActivity;
import com.lenovo.mso2o.util.DES;
import com.lenovo.mso2o.util.PrefExtraUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * configuration need to upload to the  server for next login initail
 * Created by hippo on 11/10/15.
 */
public class AccountManagerImpl implements IAccountManager {
    public static final String KEY_MSG_NOTIFY = "msg_notify";
    public static final String KEY_UPLOAD_MODE_WIFI_ONLY = "upload_mode_in_data";
    public static final String KEY_MAIN_PAGE = "main_page_tab_position";
    public static final String KEY_SCHEME_QUERY = "SCHEME_QUERY";
    public static final String KEY_PRODUCTDESCRIPTION = "PRODUCTDESCRIPTION";
    public static final String KEY_FASTBILLING = "FASTBILLING";
    public static final String KEY_MYMESSAGE = "MYMESSAGE";
    public static final String KEY_INITIATECHAT = "INITIATECHAT";
    public static final String KEY_HANDYHAVERSACK = "HANDYHAVERSACK";
    public static final AccessToken token = new AccessToken();
    private AuthAPI accountsService;
    /**
     * 当前用户nickname,为了苹果推送不是userid而是昵称
     */
    public static String currentUserNick = "";
    public static final AccountManagerImpl instance = new AccountManagerImpl();

    private AccountManagerImpl() {
        accountsService = ServiceGenerator.createService(AuthAPI.class);
    }

    public static void async() {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                AutoSignService.setDurationIfChanged(60);
                UploadService.actionStart(ContextManager.context());

                PushManager.getInstance().initialize(ContextManager.context());

                IntentFilter intentFilter = new IntentFilter();
                //addAction
                intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
                ContextManager.appContext().registerReceiver(new TickNetworkReceiver(), intentFilter);

                intentFilter = new IntentFilter();
                intentFilter.addAction(Intent.ACTION_TIME_TICK);


                ContextManager.appContext().registerReceiver(new TickNetworkReceiver.TickReceiver(), intentFilter);
            }
        });
    }

    public static void syncAppConfigJson(UserAPI userAPI, boolean upload) {
        try {
            Res<String> res = userAPI.appConfig(upload ? exportJson() + "" : "").execute().body();
            if (res != null && res.getStatus() == 1) {
                if (!upload) {
                    importJson(res.getResult());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean syncProjects(OrderAPI orderAPI) {
        try {
            Res<ArrayList<Project>> res = orderAPI.projectList().execute().body();
            if (res != null && res.getStatus() == 1) {
                ProjectDao projectDao = MSApplication.getDaoSession().getProjectDao();
                List<Project> list = projectDao.queryBuilder().list();
                projectDao.deleteAll();
//                for (Project p : list) {
//                    projectDao.delete(p);
//                }
                for (Project p : res.getResult()) {
                    projectDao.insert(p);
                }
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean syncSites(OrderAPI orderAPI) {
        try {
            Res<ArrayList<Site>> sites = orderAPI.siteList("").execute().body();
            if (sites != null && sites.getStatus() == 1) {
                SiteDao siteDao = MSApplication.getDaoSession().getSiteDao();
                List<Site> list = siteDao.queryBuilder().list();
                for (Site s : list)
                    siteDao.delete(s);
                for (Site s : sites.getResult())
                    siteDao.insert(s);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    public static void syncAds(OtherAPI otherAPI) {
        try {
            Res<ArrayList<Ad>> ads = otherAPI.adsList().execute().body();
            if (ads != null && ads.getStatus() == 1) {
                AdDao dao = MSApplication.getDaoSession().getAdDao();
                for (Ad a : ads.getResult())
                    if (null != dao.getKey(a))
                        dao.update(a);
                    else dao.insert(a);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static boolean sycUserDetail(UserAPI userAPI) {
        try {
            Observable<Res<EngineerDetailResponse>> accessTokensRxObservable = userAPI.userDetail(null);
            accessTokensRxObservable
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .unsubscribeOn(Schedulers.io())
                    .subscribe(new NetworkObserver<Res<EngineerDetailResponse>>() {
                        @Override
                        public void onSuccess(Res<EngineerDetailResponse> res) {
                            if (res.getStatus() == 1) {
                                EngineerDetailResponse resp = res.getResult();
                                PrefExtraUtils.put(MSConstants.UserInfoConstance.USER_CODE, resp.getItsmcode());
                                PrefExtraUtils.put(MSConstants.UserInfoConstance.USER_ENGINEER_ID, resp.getEngineerid());
                                PrefExtraUtils.put(MSConstants.UserInfoConstance.USER_USER_ENGINEER_NAME, resp.getName());
                                PrefExtraUtils.put(MSConstants.UserInfoConstance.USER_STATUS, resp.getStatus());
                                PrefExtraUtils.put(MSConstants.UserInfoConstance.USER_PHONE, resp.getPhone());
                                PrefExtraUtils.put(MSConstants.UserInfoConstance.USER_EMAIL, resp.getEmail());
                            }
                        }

                        @Override
                        public void onFailure(String tip) {

                        }
                    });



//            Res<MvsUser> result = userAPI.userDetail().execute().body();
//            if (result != null && result.getStatus() == 1) {
//                DLog.d("FACOUNTS", "userdetail=" + result.getMessage());
//                MvsUser user = result.getResult();
//                PrefExtraUtils.put(FConstants.UserInfoConstance.USER_ID, user.getId());
//                PrefExtraUtils.put(FConstants.UserInfoConstance.USER_CREATE_USER, user.getCreateuser());
//                PrefExtraUtils.put(FConstants.UserInfoConstance.USER_CREATE_TIME, user.getCreatetime());
//                PrefExtraUtils.put(FConstants.UserInfoConstance.USER_UPDATE_TIME, user.getUpdatetime());
//                PrefExtraUtils.put(FConstants.UserInfoConstance.USER_UPDATE_USER, user.getUpdateuser());
//                PrefExtraUtils.put(FConstants.UserInfoConstance.USER_ACCOUNT, user.getAccount());
//                PrefExtraUtils.put(FConstants.UserInfoConstance.USER_ACCOUNT_MOBILE, user.getAccountmobile());
//                PrefExtraUtils.put(FConstants.UserInfoConstance.USER_ACCOUNT_EMAIL, user.getAccountemail());
//                PrefExtraUtils.put(FConstants.UserInfoConstance.USER_PASSWORD, user.getPassword());
//                PrefExtraUtils.put(FConstants.UserInfoConstance.USER_NAME, user.getName());
//                PrefExtraUtils.put(FConstants.UserInfoConstance.USER_IP, user.getIpaddress());
//                PrefExtraUtils.put(FConstants.UserInfoConstance.USER_LASTLOGIN_TIME, user.getLastlogintime());
//                PrefExtraUtils.put(FConstants.UserInfoConstance.USER_CONFIG, user.getAppconfigjson());
//                PrefExtraUtils.put(FConstants.UserInfoConstance.USER_DELETE, user.getDelete());
//                return  true;
//
//            } else {
//
//            }
//
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//
        }
        return false;

    }

    public static boolean sycSysDics(OtherAPI otherAPI) {

        try {
            Res<ArrayList<SysDict>> result = otherAPI.dict(3).execute().body();
            if (result != null && result.getStatus() == 1) {
                SysDictDao dictDao = MSApplication.getDaoSession().getSysDictDao();
                dictDao.deleteAll();
                for (SysDict dict : result.getResult()) {
                    if (dictDao.getKey(dict) != null)
                        dictDao.update(dict);
                    else
                        dictDao.insert(dict);
                }
                return true;
            }
        } catch (Exception e) {
            DLog.p(e);
        }
        return false;
    }

    public static void asyncPersistence(final OtherAPI otherAPI, final OrderAPI orderAPI, final UserAPI userAPI) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Call<Res<Map<String, Integer>>> call =  otherAPI.appSync();
                try {
                    Res<Map<String, Integer>> res = call.execute().body();
                    final SyncCodeDao dao = MSApplication.getDaoSession().getSyncCodeDao();
                    if(res != null && res.getStatus() == 1){
                        for(final Map.Entry<String, Integer> en: res.getResult().entrySet()){
                            final List<SyncCode> syncCodes =  dao.queryBuilder().where(SyncCodeDao.Properties.Type.eq(en.getKey())).list();
                            if(syncCodes != null && syncCodes.size() > 0){
                                final SyncCode persist = syncCodes.get(0);
                                if(persist.getCode() < en.getValue()){
                                    //server version newer,upgrade
                                    if(SyncType.APP_ADDRESS.getValue().equals(en.getKey())){
                                        new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                if(syncProjects(orderAPI)){
                                                    persist.setCode((long)en.getValue());
                                                    dao.update(persist);
                                                }
                                            }
                                        }).start();
                                    }else if(SyncType.APP_SITE_LIST.getValue().equals(en.getKey())){
                                      new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                if(syncSites(orderAPI)){
                                                    persist.setCode((long)en.getValue());
                                                    dao.update(persist);
                                                }
                                            }
                                        }).start();
                                    }else if(SyncType.APP_USER.getValue().equals(en.getKey())) {
                                        new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                if(sycUserDetail(userAPI)){
                                                    persist.setCode((long)en.getValue());
                                                    dao.update(persist);
                                                }
                                            }
                                        }).start();
                                    }else if(SyncType.APP_STATUS.getValue().equals(en.getKey())){
                                        new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                if(sycSysDics(otherAPI)){
                                                    persist.setCode((long)en.getValue());
                                                    dao.update(persist);
                                                }
                                            }
                                        }).start();
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    DLog.p(e);
                }
            }
        }).start();
        //syncCidList(otherAPI);
    }

    public void setToken(AccessToken token) {
        synchronized (AccountManagerImpl.token) {
            if (token == null) {
                AccountManagerImpl.token.setToken(null);
                AccountManagerImpl.token.setRefreshtoken(null);
                AccountManagerImpl.token.setExpiretime(null);
            } else {
                AccountManagerImpl.token.setToken(token.getToken());
                AccountManagerImpl.token.setRefreshtoken(token.getRefreshtoken());
                AccountManagerImpl.token.setExpiretime(token.getExpiretime());
            }
            FPreferenceManager.putString(MSConstants.ACCESS_TOKEN, AccountManagerImpl.token.getToken());
            try {
                if (AccountManagerImpl.token.getRefreshtoken() == null)
                    FPreferenceManager.putString(MSConstants.REFRESH_TOKEN, null);
                else {
                    String desRefreshToken = DES.encryptDES(AccountManagerImpl.token.getRefreshtoken(), BuildConfig.DES_KEY);
                    FPreferenceManager.putString(MSConstants.REFRESH_TOKEN, desRefreshToken);
                    FPreferenceManager.putLong(MSConstants.REFRESH_TOKEN_TIME, System.currentTimeMillis());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public String getRefreshToken() {
        synchronized (AccountManagerImpl.token) {
            if (AccountManagerImpl.token.getRefreshtoken() == null) {
                String des2Token = FPreferenceManager.getString(MSConstants.REFRESH_TOKEN, "");
                if (!TextUtils.isEmpty(des2Token)) {
                    try {
                        String refreshToken = DES.decryptDES(des2Token, BuildConfig.DES_KEY);
                        if (!TextUtils.isEmpty(refreshToken))
                            AccountManagerImpl.token.setRefreshtoken(refreshToken);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
            DLog.w("getRefreshtoken", null == token.getRefreshtoken() ? "" : token.getRefreshtoken());
            return token.getRefreshtoken();
        }
    }

    public synchronized Res<AccessToken> refreshTokenSync() throws IOException {
        TokenRequest request = new TokenRequest();
        request.setRefreshtoken(getRefreshToken());
        Call<Res<AccessToken>> call = accountsService.refreshToken(request);
        return call.execute().body();
    }

    public AccessToken getToken(){
        return token;
    }

    public String getAccessToken() {

        synchronized (AccountManagerImpl.token) {
            if (token.getToken() == null) {
                String accessToken = FPreferenceManager.getString(MSConstants.ACCESS_TOKEN, null);
                if (!TextUtils.isEmpty(accessToken)) {
                    token.setToken(accessToken);
                }
            }
            return token.getToken();
        }
    }

    /**
     * 退出登录,清空数据
     */
    public void logout() {
        logout(null);
    }


    public static final Runnable terminateRunable = new Runnable() {
        @Override
        public void run() {
            MapManagerImpl.instance.stopLocationRealTimeSharing();
            NotificationDao dao = MSApplication.getDaoSession().getNotificationDao();
            List<Notification> notificationList = dao.queryBuilder().where(NotificationDao.Properties.Type.eq(MessageType.BILL_NUMBER.getValue())).list();
            if(notificationList != null && notificationList.size() > 0) {
                for (Notification n : notificationList)
                    dao.delete(n);
            }

        }
    };

    private Subscription _subscription;
    private Runnable logoutRunnable = new Runnable() {
        @Override
        public void run() {
            //账号登录,更新clientId, 接受登出消息
            FPreferenceManager.putBoolean(MSConstants.KEY_GETUI_INITED, false);
            FPreferenceManager.putInt(AccountManagerImpl.KEY_MAIN_PAGE, 0);
            // 先调用sdk logout，在清理app中自己的数据
            setToken(null);
            //empty use settings
            //empty sites
            final SyncCodeDao dao = MSApplication.getDaoSession().getSyncCodeDao();
            List<SyncCode>  codes = dao.queryBuilder().where(SyncCodeDao.Properties.Type.eq(SyncType.APP_SITE_LIST.getValue())).list();
            if(codes != null && codes.size() > 0){
                SyncCode code = codes.get(0);
                code.setCode((long) -1);
                dao.update(code);
            }
            //empty user profile
            PrefExtraUtils.empty();
            codes = dao.queryBuilder().where(SyncCodeDao.Properties.Type.eq(SyncType.APP_USER.getValue())).list();
            if(codes != null && codes.size() > 0){
                SyncCode code = codes.get(0);
                code.setCode((long) -1);
                dao.update(code);
            }
            NotificationDao notificationDao = MSApplication.getDaoSession().getNotificationDao();
            List<Notification> notificationList = notificationDao.queryBuilder().where(NotificationDao.Properties.Type.eq(MessageType.BILL_NUMBER.getValue())).list();
            if(notificationList != null && notificationList.size() > 0) {
                for(Notification n : notificationList)
                    notificationDao.delete(n);
            }
        }
    };

    public void logout(final EMCallBack emCallBack) {
        if (isLogin()) {
            Intent serviceIntent = new Intent(ContextManager.context(), AutoSignService.class);
            ContextManager.context().stopService(serviceIntent);
            PushManager.getInstance().stopService(ContextManager.context());
            LogoutRequest req = new LogoutRequest();
            if(_subscription == null || _subscription.isUnsubscribed())
                _subscription = accountsService.logout(req)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .unsubscribeOn(Schedulers.io())
                        .subscribe(new NetworkObserver<Res>() {
                            @Override
                            public void onSuccess(Res res) {
                                DLog.w("logout:", res + "");
                                logoutRunnable.run();
                            }

                            @Override
                            public void onFailure(String tip) {
                                //AccountManagerImpl.instance.reLogin();
                                //Toast.makeText(MainActivity.this, tip, Toast.LENGTH_SHORT).show();
                                DLog.w("logout:", "fail");
                                logoutRunnable.run();
                            }
                        });
//            asyncUnregistGeTui(logoutRunnable);
        } else {
            logoutRunnable.run();
        }
        FBaseActivity.finishAll();
    }

    public boolean isLogin() {
        long last = FPreferenceManager.getLong(MSConstants.REFRESH_TOKEN_TIME, 0);
        // 未超时并且可获取refreshtoken
        return (!(last != 0 && (System.currentTimeMillis() - last) > MSConstants.AUTHTOKEN_INVALIDE_TIME)) && (getRefreshToken() != null);
    }

    public void reLogin() {
        //check if already logged out!
        if(FBaseActivity.getActivites().size() == 1){
            if(FBaseActivity.getActivites().get(0) instanceof LoginActivity){
                return;
            }
        }
        try {
            logout();
        }catch (Exception e){
            DLog.p(e);
        }
        Intent intent = new Intent(ContextManager.context(), LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        ContextManager.appContext().startActivity(intent);
    }

    public boolean checkIn(Activity context) {
        String str2 = getRefreshToken();
        Intent intent = null;
        if (TextUtils.isEmpty(str2)) {
            intent = new Intent(context, LoginActivity.class);
        } else {
            long last = FPreferenceManager.getLong(MSConstants.REFRESH_TOKEN_TIME, 0);
            // 或者记住密码超时

            if (last != 0 && (System.currentTimeMillis() - last) > MSConstants.AUTHTOKEN_INVALIDE_TIME) {
                intent = new Intent(context,
                        LoginActivity.class);
                intent.putExtra(LoginActivity.UPDATE_TOKEN_TIME_LONG_AGO, true);
            }
        }
        if (intent != null) {
            context.overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out);
            context.startActivity(intent);
            context.finish();
            return false;

        }
        return true;
    }

    /**
     * 初始化stepIcon数据库
     */
    public static void initSyncCode(){
        SyncCodeDao syncCodeDao = MSApplication.getDaoSession().getSyncCodeDao();
        ArrayList<SyncCode> codes = (ArrayList<SyncCode>) syncCodeDao.loadAll();
        if (codes.size() != 0)
            return;
        for(SyncType t: SyncType.values()) {
            SyncCode syncCode = new SyncCode();
            syncCode.setCode((long) -1);
            syncCode.setType(t.getValue());
            syncCodeDao.insert(syncCode);
        }
    }
    /**
     * 初始化stepIcon数据库
     */
    public static void initStepIconDao() {
        StepIconDao stepDao = MSApplication.getDaoSession().getStepIconDao();
        ArrayList<StepIcon> steps = (ArrayList<StepIcon>) stepDao.loadAll();
//        if (steps.size() != 0)
//            return;
        stepDao.deleteAll();
        StepIcon icon_preCall = new StepIcon();
        icon_preCall.setName("预约");
        icon_preCall.setResId(R.drawable.icon_orderlistitem_precall);
        icon_preCall.setStep(2);
        StepIcon icon_signin = new StepIcon();
        icon_signin.setName("签到");
        icon_signin.setResId(R.drawable.icon_orderlistitem_signdin);
        icon_signin.setStep(3);
        StepIcon icon_completed = new StepIcon();
        icon_completed.setName("完成");
        icon_completed.setResId(R.drawable.icon_orderlistitem_completed);
        icon_completed.setStep(4);
        StepIcon icon_startout = new StepIcon();
        icon_startout.setName("出发");
        icon_startout.setResId(R.drawable.icon_startout);
        icon_startout.setStep(5);
        StepIcon icon_applybackup = new StepIcon();
        icon_applybackup.setName("开始服务");
        icon_applybackup.setResId(R.drawable.icon_startservice);
        icon_applybackup.setStep(6);
        StepIcon icon_service = new StepIcon();
        icon_service.setName("申请备件");
        icon_service.setResId(R.drawable.icon_applybackup);
        icon_service.setStep(7);

        stepDao.insert(icon_preCall);
        stepDao.insert(icon_signin);
        stepDao.insert(icon_completed);
        stepDao.insert(icon_startout);
        stepDao.insert(icon_applybackup);
        stepDao.insert(icon_service);
    }


    public static JSONObject exportJson(){
        try {
            JSONObject obj = new JSONObject();
            obj.put(AccountManagerImpl.KEY_FASTBILLING, FPreferenceManager.getBoolean(AccountManagerImpl.KEY_FASTBILLING, false));
            obj.put(AccountManagerImpl.KEY_HANDYHAVERSACK, FPreferenceManager.getBoolean(AccountManagerImpl.KEY_HANDYHAVERSACK, false));
            obj.put(AccountManagerImpl.KEY_INITIATECHAT, FPreferenceManager.getBoolean(AccountManagerImpl.KEY_INITIATECHAT, false));
            obj.put(AccountManagerImpl.KEY_MAIN_PAGE, FPreferenceManager.getInt(AccountManagerImpl.KEY_MAIN_PAGE, 0));
            obj.put(AccountManagerImpl.KEY_MYMESSAGE, FPreferenceManager.getBoolean(AccountManagerImpl.KEY_MYMESSAGE, false));
            obj.put(AccountManagerImpl.KEY_PRODUCTDESCRIPTION, FPreferenceManager.getBoolean(AccountManagerImpl.KEY_PRODUCTDESCRIPTION, false));
            obj.put(AccountManagerImpl.KEY_SCHEME_QUERY, FPreferenceManager.getBoolean(AccountManagerImpl.KEY_SCHEME_QUERY, false));

            return obj;
        } catch (JSONException e) {
            DLog.p(e);
        }
        return null;
    }

    public static boolean importJson(String configJson) {
        try {
            JSONObject obj = new JSONObject(configJson);
            FPreferenceManager.putBoolean(AccountManagerImpl.KEY_FASTBILLING, obj.getBoolean(AccountManagerImpl.KEY_FASTBILLING));
            FPreferenceManager.putBoolean(AccountManagerImpl.KEY_HANDYHAVERSACK, obj.getBoolean(AccountManagerImpl.KEY_HANDYHAVERSACK));
            FPreferenceManager.putBoolean(AccountManagerImpl.KEY_INITIATECHAT, obj.getBoolean(AccountManagerImpl.KEY_INITIATECHAT));
            FPreferenceManager.putInt(AccountManagerImpl.KEY_MAIN_PAGE, obj.getInt(AccountManagerImpl.KEY_MAIN_PAGE));
            FPreferenceManager.putBoolean(AccountManagerImpl.KEY_MYMESSAGE, obj.getBoolean(AccountManagerImpl.KEY_MYMESSAGE));
            FPreferenceManager.putBoolean(AccountManagerImpl.KEY_PRODUCTDESCRIPTION, obj.getBoolean(AccountManagerImpl.KEY_PRODUCTDESCRIPTION));
            FPreferenceManager.putBoolean(AccountManagerImpl.KEY_SCHEME_QUERY, obj.getBoolean(AccountManagerImpl.KEY_SCHEME_QUERY));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}

